package com.zyx.controller;

import com.wf.captcha.GifCaptcha;
import com.wf.captcha.base.Captcha;
import com.wf.captcha.utils.CaptchaUtil;
import com.zyx.mapper.UserLogMapper;
import com.zyx.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller

public class LoginController {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserLogMapper userLogMapper;

    @GetMapping("/checks")
    public void check(HttpServletResponse resp, HttpServletRequest req) throws IOException {
        GifCaptcha c = new GifCaptcha(95,36,4);
        CaptchaUtil.out(c,req,resp);
    }

    @ResponseBody
    @PostMapping("/checklogin")
    public Map<String,Object> checkLogin(@RequestBody Map<String,Object> v, HttpServletRequest req){
        Map<String,Object> map = new HashMap<>();
        map.put("code",500);
        HttpSession session = req.getSession();

        if (v.get("cc").toString().equalsIgnoreCase(session.getAttribute("captcha").toString())){ //判断验证码是否正确
            //判断登录是否成功
            if (userMapper.login(v.get("account").toString(),v.get("passwd").toString())>0){
                map.put("code",200);
                map.put("login",true);
                map.put("msg","登录成功");
                //这是session
                session.setAttribute("account",v.get("account").toString());
                //添加登录时间
                Map<String,Object> vv = new HashMap<>();
                vv.put("account",v.get("account").toString());
                vv.put("ip",req.getRemoteAddr());
                vv.put("info","登录成功");
                userLogMapper.addUserLog(vv);
            }else {
                map.put("login",false);
                map.put("msg","登录失败，请检查账号或密码");
                Map<String,Object> vv = new HashMap<>();
                vv.put("account",v.get("account").toString());
                vv.put("info","登录失败，请检查账号或密码");
                vv.put("ip",req.getRemoteAddr());
                userLogMapper.addUserLog(vv);
            }
        }else {
            map.put("login",false);
            map.put("msg","登录失败，验证码错误!");
        }
        return map;
    }
}
